<script lang="ts" setup>
  import type { CmsColumn } from '@/types/cms';
  import { onMounted, ref } from 'vue';
  import { Form, Message } from '@arco-design/web-vue';
  import { createColumn, getColumnList, updateColumn } from '@/api/cms';
  import ImageUpload from '@/components/image-upload/index.vue';
  import _ from 'lodash';
  import useTable from '@/hooks/table';

  const props = defineProps<{
    column?: CmsColumn;
  }>();

  const emit = defineEmits(['close']);

  const data = ref<Partial<CmsColumn>>({});
  onMounted(() => {
    if (props.column) {
      data.value = {
        ...props.column,
        columnPicFileList: [
          {
            status: 'done',
            uid: props.column.columnPic,
            url: props.column.columnPic,
            response: props.column.columnPic,
          },
        ],
      };
    }
  });

  const saving = ref(false);
  const formRef = ref<InstanceType<typeof Form> | null>(null);
  const handleSubmit = async () => {
    if (formRef.value) {
      const validateResult = await formRef.value.validate();
      if (!validateResult) {
        const dataCloned = _.cloneDeep(data.value);
        if (
          dataCloned.columnPicFileList &&
          dataCloned.columnPicFileList[0]?.status === 'done'
        ) {
          dataCloned.columnPic = dataCloned.columnPicFileList[0]?.response;
          delete dataCloned.columnPicFileList;
        } else {
          Message.error('请设置栏目图标');
          return;
        }

        saving.value = true;
        try {
          if (props.column) {
            await updateColumn({
              ...props.column,
              ...dataCloned,
            });
            Message.success('修改成功');
            emit('close', true);
          } else {
            await createColumn(dataCloned);
            Message.success('添加成功');
            emit('close', true);
          }
        } finally {
          saving.value = false;
        }
      }
    }
  };
</script>

<template>
  <a-modal
    :title="column ? '编辑栏目' : '添加栏目'"
    :width="500"
    visible
    :ok-loading="saving"
    @cancel="emit('close', false)"
    @before-ok="handleSubmit"
  >
    <div style="padding: 0 20px">
      <a-form ref="formRef" :model="data" layout="vertical">
        <a-form-item
          label="栏目名称"
          field="columnName"
          :rules="[{ required: true, message: '不能为空' }]"
        >
          <a-input v-model="data.columnName" />
        </a-form-item>

        <a-form-item
          label="栏目图标"
          field="columnPicFileList"
          :rules="[{ required: true, message: '不能为空' }]"
        >
          <ImageUpload
            v-model="data.columnPicFileList"
            :max-size="1024 * 1024"
            :limit="1"
            should-square
          />
          <template #extra> 请上传长宽比为1：1的图片，不大于1MB </template>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>
